package com.fjec.devops.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fjec.common.jxls.ExchangeGiftExcel;
import com.fjec.common.view.DevopsExchangeGiftVO;
import com.fjec.devops.entity.BizExchangeGiftExcel;
import com.fjec.devops.feign.ActivityClient;
import com.fjec.devops.feign.BaseClient;
import com.fjec.devops.mapper.BizExchangeGiftExcelMapper;
import com.fjec.devops.service.IBizExchangeGiftExcelService;
import com.fjec.devops.view.ExchangeGiftExcelVO;
import com.fjec.common.Const;
import com.fjec.common.enums.EnumSysCode;
import com.fjec.common.exception.BizException;
import com.fjec.common.protocol.JsonResult;
import com.fjec.common.util.Base64Util;
import com.fjec.common.util.DateUtil;
import com.fjec.common.util.SequenceIdGenerator;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.io.FileUtils;
import org.jxls.common.Context;
import org.jxls.util.JxlsHelper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 012.礼物兑换Excel下载表 服务实现类
 * </p>
 *
 * @author admin
 * @since 2020-12-08
 */
@Service
public class BizExchangeGiftExcelServiceImpl extends ServiceImpl<BizExchangeGiftExcelMapper, BizExchangeGiftExcel> implements IBizExchangeGiftExcelService {

    @Resource
    private BizExchangeGiftExcelMapper mapper;

    @Resource
    private ActivityClient activityClient;

    @Resource
    private SequenceIdGenerator idGenerator;

    @Resource
    private BaseClient baseClient;

    @Override
    public boolean dateIsHandled(LocalDate date) {
        QueryWrapper<BizExchangeGiftExcel> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("GenerateDate", date);
        int count = mapper.selectCount(queryWrapper);
        return count > 0;
    }

    @Override
    public void uploadExcels(LocalDate date) throws Exception {
        // 查询数据
        List<ExchangeGiftExcel> dataList = activityClient.getExchangeGiftForExcel(DateUtil.format(date, "yyyyMMdd"));
        if (dataList != null && !dataList.isEmpty()) {
            // generate id
            Long id = idGenerator.nextId();
            Long annexId = 0L;
            // 生成Excel并上传
            try (InputStream is = this.getClass().getResourceAsStream("/excelTemplate/exchange_gift_template.xlsx")) {
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                Context context = new Context();
                context.putVar("dataList", dataList);
                JxlsHelper.getInstance().processTemplate(is, bos, context);
                byte[] fileBytes = bos.toByteArray();
                String fileName = Const.EXCHANGE_GIFT_EXCEL_FILE_NAME.replace("{0}", DateUtil.format(date, "yyyyMMdd"));
                Map<String, Object> tmpMap = baseClient.base64Upload(
                        Base64Util.encode(fileBytes),
                        fileName,
                        114,
                        id,
                        0
                );
                FileUtils.writeByteArrayToFile(new File(String.format("D:\\%s", fileName)), fileBytes);
                annexId = MapUtils.getLong(tmpMap, "id");
            }
            // 写入数据库
            if (annexId > 0) {
                BizExchangeGiftExcel entity = new BizExchangeGiftExcel();
                entity.setId(id);
                entity.setFile1Id(annexId);
                entity.setFile2Id(annexId);
                entity.setGenerateDate(date);
                entity.setHandled(0);
                entity.setCreateTime(DateUtil.nowLdt());
                mapper.insert(entity);
            } else {
                throw new BizException(EnumSysCode.ERR_3030.getCode(), EnumSysCode.ERR_3030.getMsg());
            }
        }
    }

    @Override
    public JsonResult getEntityListPage(Page page) throws Exception {
        QueryWrapper<BizExchangeGiftExcel> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("GenerateDate");
        Page<BizExchangeGiftExcel> returnPage = mapper.selectPage(page, queryWrapper);
        List<ExchangeGiftExcelVO> resultList = new ArrayList<>();
        for (BizExchangeGiftExcel entity : returnPage.getRecords()) {
            ExchangeGiftExcelVO view = new ExchangeGiftExcelVO();
            BeanUtils.copyProperties(view, entity);
            view.setHandledFile((entity.getHandled() & 1) == 1);
//            view.setHandledFile2((entity.getHandled() & 2) == 2);
            resultList.add(view);
        }
        return JsonResult.success()
                .total(returnPage.getTotal())
                .data(resultList)
                .build();
    }

    @Override
    public void downloadExcel(Long id, Long downloadId, HttpServletResponse res) throws Exception {
        BizExchangeGiftExcel entity = mapper.selectById(id);
        if (entity != null) {
            // 更新下载状态
            if ((entity.getHandled() & 1) != 1) {
                entity.setHandled(entity.getHandled() + 1);
                entity.setUpdateTime(DateUtil.nowLdt());
                mapper.updateById(entity);
            }
            // rpc下载文件
            Map<String, Object> map = baseClient.getOSSFileBase64ById(downloadId);
            if (map != null && !map.isEmpty()) {
                String fileName = MapUtils.getString(map, "fileName");
                String base64 = MapUtils.getString(map, "base64");
                byte[] bytes = Base64Util.decode2Bytes(base64);
                res.reset();
                res.setContentType("application/octet-stream");
                res.addHeader("filename", URLEncoder.encode(fileName, "UTF-8"));
                res.addHeader("Access-Control-Expose-Headers", "filename");
                OutputStream out = res.getOutputStream();
                out.write(bytes, 0, bytes.length);
                out.flush();
            }
        }
    }

    @Override
    public JsonResult getExchangeGiftPage(Page page, Integer searchBy, String condition, String startTime, String endTime) {
        Map<String, Object> resultMap = activityClient.getExchangeGiftPage(
                page.getCurrent(),
                page.getSize(),
                searchBy,
                condition,
                startTime,
                endTime
        );
        List<DevopsExchangeGiftVO> viewList = new ArrayList<>();
        long total = MapUtils.getLongValue(resultMap, "total", 0L);
        Object obj = MapUtils.getObject(resultMap, "list", null);
        if (obj != null) {
            viewList = (List<DevopsExchangeGiftVO>) obj;
        }
        return JsonResult.success()
                .total(total)
                .data(viewList)
                .build();
    }
}
